const CommonApi = require('../../api/common.js');
const QuoteApi = require('../../api/quote.js');
const {optionalColumns} = require('../../utils/data.js');
const cityJson = require('../../utils/city.js');
const commonUtil = require('../../utils/common.js');
const util = require("../../utils/util.js")

Page({
  data: {
    tableInfo: {
      columns: optionalColumns,
      data: [],
      offsetLeft: 0,
    },
    currentQuoteGroupName: null,
    currentRow: null,
    dialogVisible: false,
    _globalData: null
  },
  onShow() {
    if (typeof this.getTabBar === 'function' &&  this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }

    this.getLocationInfo()
    this.initData()

    if (this.data._globalData.token) {
      commonUtil.getUserServiceState();
      this.setData({['_globalData.userService']: wx.getStorageSync('userService')})
      if (this.data._globalData.userService) {
        this.getModalContent();
        if (['progress', 'expire', 'expiring'].includes(this.data._globalData.userService.state)) {
          this.getFollowQuoteList()
        } else {
          this.getRecommendQuoteGroup()
        }

        if (this.data._globalData.userService.state !== 'progress') {
          this.setData({
            dialogVisible: true
          })
          setTimeout(()=>{
            this.setData({dialogVisible: false})
          }, 3000)
        }
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: '请先登录后查看',
      })
      setTimeout(()=>{
        wx.redirectTo({
          url: '/packageA/pages/login/index?redirect_uri=/pages/optional/index&redirect_uri_type=tab',
        })
      }, 2000)
    }
  },
  onHide(){
    this.initData()
  },
  onUnload(){
    this.setData({['tableInfo.data']: []})
    this.initData()
  },
  initData(){
    wx.pageScrollTo({
      selector: '.optionalPage',
      scrollTop: 0,
    });

    let token = wx.getStorageSync('token');
    let userService = wx.getStorageSync('userService');
    this.setData({
      ['_globalData.token']: token,
      ['_globalData.userService']: userService,
      ['tableInfo.offsetLeft']: 0
    })
  },
  // 前端自选页面自选报价查询
  getFollowQuoteList(){
    QuoteApi.getFollowQuoteList({quoteDate: null}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        if (res.data) {
          let array = [];
          if (res.data.length > 0) {
            array = res.data.map(item=>{
              if (item.lowestPrice) item.lowestPrice = util.bigNumberFixed(item.lowestPrice, 0)
              if (item.highestPrice) item.highestPrice = util.bigNumberFixed(item.highestPrice, 0)
              if (item.averagePrice) item.averagePrice = util.bigNumberFixed(item.averagePrice, 0)
              if (item.upsDowns) item.upsDowns = util.bigNumberFixed(item.upsDowns, 0)
              if (item.price) item.price = util.bigNumberFixed(item.price, 0)
              if (item.quoteDate) item.quoteDate = util.formatDate(item.quoteDate, 'MM-DD')
              return item;
            })
          }
          this.setData({
            ['tableInfo.data']: array
          })

          if (res.data.length === 0 && (_globalData.userService && ['progress', 'expire', 'expiring'].includes(_globalData.userService.state))) {
            this.getRecommendQuoteGroup()
          }
        } else {
          this.setData({
            ['tableInfo.data']: []
          })
        }
      }
    })
  },
  // 前段根据地区查询报价单
  getRecommendQuoteGroup(){
    QuoteApi.getRecommendQuoteGroup({visitorArea: null}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        if (res.data) {
          let array = [];
          if (res.data.list.length > 0) {
            array = res.data.list.map(item=>{
              if (item.lowestPrice) item.lowestPrice = util.bigNumberFixed(item.lowestPrice, 0)
              if (item.highestPrice) item.highestPrice = util.bigNumberFixed(item.highestPrice, 0)
              if (item.averagePrice) item.averagePrice = util.bigNumberFixed(item.averagePrice, 0)
              if (item.upsDowns) item.upsDowns = util.bigNumberFixed(item.upsDowns, 0)
              if (item.price) item.price = util.bigNumberFixed(item.price, 0)
              if (item.quoteDate) item.quoteDate = util.formatDate(item.quoteDate, 'MM-DD')
              return item;
            })
          }
          this.setData({
            currentQuoteGroupName: res.data.quoteGroupName,
            ['tableInfo.data']: array
          })
        } else {
          this.setData({
            ['tableInfo.data']: []
          })
        }
      }
    })
  },
  // 获取当前位置信息
  getLocationInfo(){
    CommonApi.getLocationInfo().then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        let obj = cityJson.default.find(i=>i.isoCode == res.data.provinceCode);
        if (obj) {
          wx.setStorageSync('currentProvince', obj);
        } else {
          wx.removeStorageSync('currentProvince');
        }
      }
    })
  },
  // 添加或取消自选
  followQuote(_quoteId){
    QuoteApi.followQuote({quoteId: _quoteId}).then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        wx.showToast({
          icon: 'success',
          title: res.errMsg,
        })
        this.getFollowQuoteList();
      } else {
        wx.showToast({
          icon: 'error',
          title: res.errMsg,
        })
        if (res.errCode == '999901') {
          redirectCurrent()
        }
      }
    })
  },
  // 自选操作
  toSave(e){
    let currentItem = e.currentTarget.dataset.item;
    if (this.data._globalData.token) {
      if (this.data._globalData.userService && ['progress', 'expire', 'expiring'].includes(this.data._globalData.userService.state)) {
        this.followQuote(currentItem.quoteId)
      } else {
        this.setData({dialogVisible: true})
        setTimeout(()=>{
          this.setData({dialogVisible: false})
        }, 3000)
      }
    } else {
      wx.showToast({
        icon: 'none',
        title: '请先登录',
      })
    }
  },
  // 登录后跳转回当前页
  redirectCurrent(){
    wx.removeStorage({key: 'token'});
    wx.removeStorage({key: 'userInfo'});
    setTimeout(()=>{
      wx.redirectTo({
        url: '/packageA/pages/login/index?redirect_uri=/pages/optional/index&redirect_uri_type=tab',
      })
    }, 2000)
  },
  getModalContent(){
    let obj = {title: null, content: null};
    let userService = wx.getStorageSync('userService');
    if (userService) {
      if (userService.state === 'apply') {
        obj.title = '行情数据为收费服务';
        obj.content = '新客户可申请7天免费试用';
      } else if (userService.state === 'checking') {
        obj.title = '7天免费试用申请成功';
        obj.content = '审核通过后服务自动开通，请等待后台审核。';
      } else if (userService.state === 'start') {
        obj.title = '您订购的数据服务待生效';
        obj.content = `生效日期：${userService.openDate}~${userService.endDate}<br/>如有疑问，请联系客服。`;
      } else if (userService.state === 'expire') {
        obj.title = '您订购的数据服务将过期';
        obj.content = '为了不影响您的正常使用，请及时联系客服续约。';
      } else if (userService.state === 'expiring') {
        obj.title = '您订购的数据服务马上过期';
        obj.content = '为了不影响您的正常使用，请及时联系客服续约。';
      } else if (userService.state === 'expired') {
        obj.title = '您订购的数据服务已过期';
        obj.content = '行情数据服务：600元/年<br/>如需继续使用，请联系客服续约。';
      }
      this.setData({
        modalContent: obj
      })
    }
  },

})